# -*- coding: UTF-8 -*- 
import numpy as np
import caffe
from PIL import Image,ImageDraw
# 加载模型
net = caffe.Net('a.prototxt', 'a.caffemodel', caffe.TEST)



image_path = '/home/gl/Downloads/16.jpg'
img = Image.open(image_path)
img_resized = img.resize((640, 640), Image.BICUBIC)  # 调整图片大小至模型输入尺寸
img_array = np.array(img_resized, dtype=np.float32)  # 转换为numpy数组

# RGB转BGR（因为OpenCV默认是BGR，而Caffe可能期待BGR顺序）
img_array = img_array[:, :, ::-1]

# 图像归一化（这一步依赖于模型训练时使用的归一化方式，常见的做法是减去均值并除以标准差）
mean = np.array([0.485, 0.456, 0.406])  # 这些值是ImageNet预训练模型常用的
std = np.array([0.229, 0.224, 0.225])
img_array = (img_array / 255.0 - mean) / std

# 调整数组形状以匹配网络输入
img_array = np.transpose(img_array, (2, 0, 1))  # 将HWC转换为CHW
img_array = np.expand_dims(img_array, axis=0)  # 添加批量维度

net.blobs['images'].data[...] = img_array

# 执行前向传播
output = net.forward()
print(output.keys()) #['output', '362', '350']

# 输出或处理结果
#res = output['362']
print(output['362'].shape)
print(output['350'].shape)
print(output['output'].shape)
print(output['output'][0][0][0][0])
print(output['output'][0][0][0][1])
print(output['output'][0][0][1][1])

o1 = output['output'][0][0][0][1]
# 使用Numpy的exp函数计算e的指数
exp_values = np.exp(-o1)

# 计算Sigmoid函数值
sigmoid_values = 1 / (1 + exp_values)

# 提取第五个元素（对象存在置信度）的Sigmoid值
obj_confidence = sigmoid_values[4]

# 提取后六个元素（假设为类别概率）的Sigmoid值
class_probabilities = sigmoid_values[5:]*obj_confidence

print("obj confidence sigmoid:", obj_confidence)
print("cls probility sigmoid:", class_probabilities)




print(" --------little--------  ")
allobj_confidence=output['output'][:, :, :, :, 4] 
all_score = 1 / (1 + np.exp(-allobj_confidence))
print("output shape:",allobj_confidence.shape)
max_confidence_in_array = np.max(all_score)
max_coords_direct = np.unravel_index(np.argmax(all_score, axis=None), all_score.shape)
print("max_confidence_in_array:", max_confidence_in_array)
print("norm_loc:", np.divide(max_coords_direct,80.0))
print("max_coords_direct:", max_coords_direct)

print(" --------middle--------  ")
allobj_confidence=output['350'][:, :, :, :, 4] 
all_score = 1 / (1 + np.exp(-allobj_confidence))
print("output shape:",allobj_confidence.shape)
max_confidence_in_array = np.max(all_score)
max_coords_direct = np.unravel_index(np.argmax(all_score, axis=None), all_score.shape)
print("max_confidence_in_array:", max_confidence_in_array)
print("norm_loc:", np.divide(max_coords_direct,40.0))
print("max_coords_direct:", max_coords_direct)

print(" --------large--------  ")
allobj_confidence=output['362'][:, :, :, :, 4] 
all_score = 1 / (1 + np.exp(-allobj_confidence))
print("output shape:",allobj_confidence.shape)
max_confidence_in_array = np.max(all_score)
max_coords_direct = np.unravel_index(np.argmax(all_score, axis=None), all_score.shape)
print("max_confidence_in_array:", max_confidence_in_array)
print("norm_loc:", np.divide(max_coords_direct,20.0))
print("max_coords_direct:", max_coords_direct)



#img.show()

width,height = img.size
bbox_size_x = width * 0.05
bbox_size_y = height * 0.05
row = np.divide(max_coords_direct,20.0)[2] 
col = np.divide(max_coords_direct,20.0)[3] 
print(row,col)
x =col  *width
y = row  *height
end_x = x + bbox_size_x
end_y = y + bbox_size_y
draw = ImageDraw.Draw(img)
draw.rectangle([x,y,end_x,end_y],outline='red',width=2)
img.show()


print(" --------sum--------  ")
flat_obj_confidence = all_score.flatten()
max_confidence = np.max(flat_obj_confidence)
print("max_score sigmoid:", max_confidence)

#print(res[0][0][0][0])
#print(detection_results)
